/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - core/system/io/platform/posix
// Copyright (c) 2014.  All Rights Reserved
//
// File:		AEPosixStreamReader.cpp
// Author:		Gianluca Belardelli
// Date:		11/10/2013
//
/////////////////////////////////////////////////////////////////////////
#include <AECore.h>
#include <core/system/io/platform/posix/AEPosixStreamReader.h>

AEPosixStreamReader *AEPosixStreamReader::Open( const char *lpName )
{
	FILE *fp = fopen( lpName, "rb" );
	if( fp )
		return new AEPosixStreamReader( (AEINT32)fp );

	return NULL;
}

AEPosixStreamReader::AEPosixStreamReader( AEINT32 nFileHanlde )
{
	m_nFileHandle = nFileHanlde;
	m_nLastError = 0;
}

AEPosixStreamReader::~AEPosixStreamReader( void )
{
	Close();
}

void AEPosixStreamReader::Close( void )
{
	FILE *fp = (FILE *)m_nFileHandle;
	fclose( fp );
	m_nFileHandle = -1;
}

int AEPosixStreamReader::Read( void *lpBuf, AEINT32 nBytes )
{
	if( m_nFileHandle == -1 )
		return 0;

	FILE *fp = (FILE *)m_nFileHandle;
	size_t sRet = fread( lpBuf, nBytes, 1, fp );
	return sRet;
}

int AEPosixStreamReader::Skip( AEINT32 nBytes )
{
	if( m_nFileHandle == -1 )
		return 0;

	FILE *fp = (FILE *)m_nFileHandle;
	return fseek( fp, nBytes, SEEK_CUR );
}

int AEPosixStreamReader::Peek( void *lpBuf, AEINT32 nBytes )
{
	if( m_nFileHandle == -1 )
		return 0;

	FILE *fp = (FILE *)m_nFileHandle;
	size_t sRet = fread( lpBuf, nBytes, 1, fp );
	return fseek( fp, -nBytes, SEEK_CUR );
}

AERESULT AEPosixStreamReader::GetLastError( void ) const
{
	if( m_nFileHandle == -1 )
		return 0;

	return m_nLastError;
}

AERESULT AEPosixStreamReader::Seek( AEINT32 nOffset, AESeekOptions soOpt )
{
	if( m_nFileHandle == -1 )
		return 0;

	FILE *fp = (FILE *)m_nFileHandle;
	return fseek( fp, nOffset, soOpt );
}

AEINT32 AEPosixStreamReader::Tell( void ) const
{
	if( m_nFileHandle == -1 )
		return 0;

	FILE *fp = (FILE *)m_nFileHandle;
	return ftell( fp );
}
